import { navigateBack } from '@/router';
import { onUnload } from '@dcloudio/uni-app';
import { computed, isRef, ref, watch, type Ref } from 'vue';

export interface UseNavigateBackOptions {
  /** 是否拦截返回 */
  enableBeforeUnload?: boolean
  /** 物理返回拦截提醒文案 */
  backMessage?: string
  /** 拦截弹窗配置 */
  showModalOptions: Omit<UniApp.ShowModalOptions, 'success' | 'fail' | 'complete'>
  /** 拦截弹窗确认回调 */
  confirmCallback?: (result: UniApp.ShowModalRes) => Promise<void>
}

export function useBackBeforeUnload(options?: UseNavigateBackOptions | Ref<UseNavigateBackOptions>) {
  const op = isRef(options) ? options : ref(options)

  function interceptNavigateBack(delta = 1) {
    if (op.value?.enableBeforeUnload) {
      uni.showModal({
        ...op.value.showModalOptions,
        success: async (res) => {
          if (res.confirm) {
            await op.value?.confirmCallback?.(res)
          }
          UniNavigateBack();
        },
      });
    } else {
      UniNavigateBack();
    }
  }

  function UniNavigateBack() {
    hideUnloadAlert();
    navigateBack();
  }

  function showUnloadAlert() {
    uni.enableAlertBeforeUnload({
      message: op.value?.backMessage || '确认返回',
    });
  }

  function hideUnloadAlert() {
    uni.disableAlertBeforeUnload();
  }

  if (op.value) {
    watch(() => op.value?.enableBeforeUnload, val => {
      val ? showUnloadAlert() : hideUnloadAlert()
    }, { immediate: true })
  }

  onUnload(() => hideUnloadAlert());

  return {
    interceptNavigateBack,
    UniNavigateBack,
  };
}
